#! /usr/bin/env python
#coding=utf-8
import  sys,urllib2,json,time,datetime
import MySQLdb
import multiprocessing
reload(sys)

#正式连接-----------
#host = "drdsrtok600s5n74.drds.aliyuncs.com"
#user = "hefantv"
#passwd = "HEfantv3_9a5"
#db = "hefantv"
#测试连接--------------
# host = "drdsjsq4v76a23pa.drds.aliyuncs.com"
# user = "hefantest"
# passwd = "HEfantv3_9a5"
# db = "hefantest"
#开发连接--------------
host = "drdshmif9192k8au.drds.aliyuncs.com"
user = "hefandev"
passwd = "devhfDEV8v97"
db = "hefandev"
port = 3306
charset='utf8'

#每天预处理需检查的记录数
maxCount = 50000
#测试使用前缀用户注册token的前缀
prefix = ""
#获取token的请求地址
#开发地址
#tokenUrl = "http://47.93.91.24:8055"
#QA请求地址
tokenUrl = "http://101.200.198.81:8055"
#生产请求地址
#tokenUrl = "http://10.51.68.107:8055"
#融云获取token所需默认的头像地址
defalutHeadImg = "http://img.hefantv.com/default_head.png"

#获取预处理数据未成功的用户数据
def getNeedUserInfo(runType,checkDate):
    queryStr = ''
    if runType == 1 :
        queryStr = """im_token_ry = ''"""
    elif runType == 2:
        queryStr = """im_token = ''"""
    else:
        return None
    connect = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
    cursor = connect.cursor()
    sql = """select user_id FROM hf_user_pre_init
    where create_time BETWEEN '%s 00:00:00' AND '%s 23:59:59' and %s limit %d"""%(checkDate,checkDate,queryStr,maxCount)
    cursor.execute(sql)
    data = cursor.fetchall()
    cursor.close()
    connect.close()
    return data

#更新补充的token信息
def updateUserPreInfo(connect,runType,userId,token):
    updateSqlStr = ""
    if runType == 1 :
        updateSqlStr = """im_token_ry = '%s'"""%(token)
    elif runType == 2:
        updateSqlStr = """im_token = '%s'"""%(token)
    else:
        return None
    sql = "update hf_user_pre_init set %s where user_id='%s'"%(updateSqlStr,userId)
    cursor = connect.cursor()
    cursor.execute(sql)
    connect.commit()
    cursor.close()

#
# 获取云信im的token
#
def getYxImToken(userId) :
    reqUrl = "%s/services/imUser/createUser?accid=%s&name=%s" % (tokenUrl,userId,userId)
    req = urllib2.Request(reqUrl)
    res_data = urllib2.urlopen(req, timeout=10)
    resData = json.loads(res_data.read())
    print "YxRequestData-------", resData;
    if resData["code"] == 1000 and resData["data"] :
        return resData["data"]
    else:
        return ""

#
# 获取融云im的token
#
def getRyTokenReq(userId) :
    reqUrl = "%s/services/rongIm/getToken?userId=%s&name=%s&portraitUri=%s" % (tokenUrl, userId, userId,defalutHeadImg)
    req = urllib2.Request(reqUrl)
    res_data = urllib2.urlopen(req, timeout=10)
    resData = json.loads(res_data.read())
    print "RyRequestData-------",resData;
    time.sleep(0.005)
    if resData["code"] == 1000 and resData["data"] :
        return resData["data"]
    else:
        return ""

#获取IM的token的总入口方法
def getToken(runType,userId):
    token = ""
    if runType == 1:
        token = getRyTokenReq(prefix+userId)
    elif runType == 2:
        token = getYxImToken(prefix+userId)
    return token

#预处理用户token未获取时进行
def userPreCheckHandler(runType,userIds):
    connect = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
    for userId in userIds :
        token = getToken(runType,userId[0])
        if token:
            updateUserPreInfo(connect,runType,userId[0],token)
    connect.close()


if __name__ == '__main__':
    beginTime = time.clock()
    runDate = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S');
    # 根据执行脚本的入参判断   1 补充融云IM的token  2 补充云信IM的token
    runType = 1
    if len(sys.argv) <= 1 :
        runType = 1
    else:
        runType = int(sys.argv[1])
    if runType == 1 or runType == 2 :
        checkDate = datetime.datetime.strftime(datetime.datetime.now() - datetime.timedelta(days=1), '%Y-%m-%d')
        userIds = getNeedUserInfo(runType,checkDate)
        print "---query error pre num---",len(userIds)
        if len(userIds) > 0 :
            userPreCheckHandler(runType,userIds)
        else:
            print "no error pre info"
    else :
        print "needed arg 1 or 2 "
    print "user pre check end date:[%s] time:%d s" % (runDate,time.clock() - beginTime)